<template>
  <div class="teacher-component" v-loading="loading">
    <div class="teacher-layout">
      <!-- 左侧年级树形结构 -->
      <div class="grade-tree-container">
        <div class="tree-header">
          <i class="el-icon-school"></i> 年级
        </div>
        <div class="tree-content">
          <el-tree
            ref="gradeTree"
            :data="treeData"
            node-key="id"
            :props="defaultProps"
            :highlight-current="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            :current-node-key="currentNode ? currentNode.id : 'all'"
            default-expand-all
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span :class="{'node-selected': currentNode && currentNode.id === data.id}">
                  {{ node.label }} 
                  <span v-if="data.count && data.count > 0" class="count-tag">({{ data.count }})</span>
                </span>
              </span>
            </template>
          </el-tree>
          <div v-if="treeData.length === 0" class="empty-tree">
            <i class="el-icon-warning-outline"></i>
            <p>暂无年级数据</p>
          </div>
        </div>
      </div>

      <!-- 右侧教师列表 -->
      <div class="teacher-list-container">
        <!-- 顶部标题和搜索区域 -->
        <div class="grade-info-header">
          <div class="header-row">
            <div class="grade-title">
              <h2>{{ currentNode ? currentNode.label : '全部年级' }}</h2>
              <span class="subtitle">教师管理 ({{ teacherCount }})</span>
            </div>
            
            <!-- 搜索区域放在同一行 -->
            <div class="search-section">
              <el-select v-model="subjectId" class="filter-select" size="small" placeholder="全部科目" clearable>
                <el-option
                  v-for="{ id, name } in subjectList"
                  :label="name"
                  :value="id"
                  :key="id"
                >
                </el-option>
              </el-select>
              <el-input
                class="search-input"
                v-model="teacherName"
                prefix-icon="el-icon-search"
                placeholder="请输入老师姓名/手机查询"
                @input="inputChange"
                clearable
                size="small"
              ></el-input>
            </div>
          </div>
        </div>

        <!-- 可滚动的内容区域 -->
        <div class="scrollable-content">
          <!-- 教师管理部分 -->
          <div class="teacher-section">
            <!-- 功能按钮区域 -->
            <div class="action-buttons">
                <ButtonPermission code="teacher:add" mode="disable">
                  <template #default="{ disabled }">
                    <el-dropdown :disabled="disabled" @command="handleCommand" trigger="click">
                      <el-button type="primary" size="small" icon="el-icon-plus" :disabled="disabled">
                        新增<i class="el-icon-arrow-down el-icon--right"></i>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="add-teacher">单个新增</el-dropdown-item>
                          <ButtonPermission code="teacher:import" mode="disable">
                            <template #default="{ disabled: importDisabled }">
                              <el-dropdown-item command="import-teacher" :disabled="importDisabled">批量导入</el-dropdown-item>
                            </template>
                          </ButtonPermission>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </template>
                </ButtonPermission>
                <ButtonPermission code="teacher:update" mode="disable">
                  <template #default="{ disabled }">
                    <el-button 
                      type="primary" 
                      size="small" 
                      :disabled="disabled"
                      @click="!disabled && updateTeacher()" 
                      icon="el-icon-refresh"
                    >更新</el-button>
                  </template>
                </ButtonPermission>
                <ButtonPermission code="teacher:export" mode="disable">
                  <template #default="{ disabled }">
                    <el-button 
                      type="primary" 
                      size="small" 
                      :disabled="disabled"
                      @click="!disabled && exportTeacher()" 
                      icon="el-icon-download"
                    >导出</el-button>
                  </template>
                </ButtonPermission>
                <ButtonPermission code="teacher:resetPwd" mode="disable">
                  <template #default="{ disabled }">
                    <el-button 
                      type="primary" 
                      size="small" 
                      :disabled="disabled"
                      @click="!disabled && batchResetPwd()" 
                      icon="el-icon-key"
                    >重置密码</el-button>
                  </template>
                </ButtonPermission>
                <ButtonPermission code="teacher:clear" mode="disable">
                  <template #default="{ disabled }">
                    <el-button 
                      type="danger" 
                      size="small" 
                      :disabled="disabled"
                      @click="!disabled && clearAllTeacher()" 
                      icon="el-icon-delete"
                    >清空教师</el-button>
                  </template>
                </ButtonPermission>
            </div>
            
            <div class="table-wrapper">
              <el-table
                :data="teachersInfo"
                stripe
                border
                :max-height="tableMaxHeight"
                header-cell-class-name="table-header"
                empty-text="暂无教师数据"
              >
                <el-table-column label="姓名" prop="F_name" align="center" width="120"></el-table-column>
                <el-table-column label="性别" prop="F_gender_name" align="center" width="80"></el-table-column>
                <el-table-column label="手机/登录名" prop="F_phone" align="center" width="120"></el-table-column>
                <el-table-column label="账号" prop="F_account" align="center" width="120"></el-table-column>
                <el-table-column label="授课科目" prop="" align="center" min-width="120">
                  <template #default="scope">
                    <div class="cell-content">
                      <template v-if="scope.row.teach_subject_list && scope.row.teach_subject_list.length > 0">
                        <el-tag
                          v-for="item in scope.row.teach_subject_list"
                          :key="item.id"
                          size="small"
                          type="info"
                          class="subject-tag"
                        >
                          {{ item.name }}
                        </el-tag>
                      </template>
                      <span v-else class="empty-text">-</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="授课班级" prop="" align="center" min-width="150">
                  <template #default="scope">
                    <div class="cell-content">
                      <template v-if="scope.row.F_teach_list && scope.row.F_teach_list.length > 0">
                        <div
                          v-for="item in scope.row.F_teach_list"
                          :key="item.F_id + '_' + item.F_subject"
                          class="teach-class-item"
                        >
                          {{ item.F_name }} {{ item.F_subject_name }}
                        </div>
                      </template>
                      <span v-else class="empty-text">-</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="班主任" prop="" align="center" min-width="120">
                  <template #default="scope">
                    <div class="cell-content">
                      <template v-if="scope.row.F_manager_class && scope.row.F_manager_class.length > 0">
                        <el-tag
                          v-for="item in scope.row.F_manager_class"
                          :key="item.F_id"
                          size="small"
                          type="success"
                          class="manager-tag"
                        >
                          {{ item.F_name }}
                        </el-tag>
                      </template>
                      <span v-else class="empty-text">-</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" prop="" align="center" fixed="right" width="140">
                  <template #default="scope">
                    <div class="action-buttons-cell">
                      <ButtonPermission code="teacher:edit" mode="disable">
                        <template #default="{ disabled }">
                          <el-button 
                            type="text" 
                            size="small" 
                            class="edit-btn" 
                            :disabled="disabled"
                            @click="!disabled && editTeacher(scope.row)"
                          >编辑</el-button>
                        </template>
                      </ButtonPermission>
                      <ButtonPermission code="teacher:delete" mode="disable">
                        <template #default="{ disabled }">
                          <el-button 
                            type="text" 
                            size="small" 
                            class="delete-btn"
                            :disabled="disabled"
                            @click="!disabled && deleteTeacher(scope.$index, scope.row)"
                          >删除</el-button>
                        </template>
                      </ButtonPermission>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <div class="footer">
              <el-pagination
                background
                layout="total, prev, pager, next"
                :total="teacherCount"
                @current-change="changePage"
                v-model:current-page="page"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>

    <edit-teacher
      v-if="showEditTeacher"
      :teacher="teacher"
      :type="type"
      :page="page"
      @getTeachers="getTeachers"
      @update="updateEdit"
    ></edit-teacher>
    <ResetPW
      v-if="showResetPassword"
      :schoolId="schoolId"
      :gradeAndClass="gradeAndSubject.F_grades || {}"
      @close="showResetPassword = false"
    />
    <SetAccount
      v-if="showAccountSetting"
      @update="getTeachers"
      @close="showAccountSetting = false"
    />
  </div>
</template>

<script>
import { downloadExcelBlob, debounce } from '@/utils/utils';
import editTeacher from './editTeacher.vue';
import ResetPW from './ResetPW.vue';
import SetAccount from './SetAccount.vue';
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
  components: {
    editTeacher,
    ResetPW,
    SetAccount,
  },
  props: {
    schoolId: {
      type: [Number, String],
      required: false,
      default: null
    },
    updateMsg: {
      type: Number,
      default: 0
    },
  },
  data() {
    return {
      type: 1,
      loading: false,
      gradeAndSubject: {},
      gradeList: [],
      subjectList: [],
      genderList: [
        { id: 0, name: '-' },
        { id: 1, name: '男' },
        { id: 2, name: '女' }
      ],
      gradeId: 0,
      subjectId: 0,
      genderId: 0,
      teacherName: '',
      page: 1,
      teachersInfo: [],
      teachers: [],
      teacher: {},
      teacherCount: 0,
      showEditTeacher: false,
      isAddTeacher: false,
      showResetPassword: false,
      showAccountSetting: false,
      // 年级树形结构相关数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentNode: null,
      tableMaxHeight: 'calc(100vh - 250px)',
    };
  },

  computed: {
    ...mapState('school', ['schoolOptions']),
    ...mapGetters('school', ['schoolName', 'schoolSubjectList']),
  },
  watch: {
    // 监听 schoolOptions 变化，确保数据加载后重新初始化
    schoolOptions: {
      handler(newVal) {
        if (newVal && newVal.F_grades && Object.keys(newVal.F_grades).length > 0) {
          // 只有当 schoolOptions 有有效数据时才初始化
          this.gradeAndSubject = JSON.parse(JSON.stringify(newVal));
          this.getGradeList();
          this.getSubjectList();
          this.buildGradeTree();
          
          // 确保默认选中"全部年级"节点
          if (this.treeData && this.treeData.length > 0) {
            this.currentNode = this.treeData[0];
            this.gradeId = 0; // 默认显示全部年级的教师
          }
          
          // 如果还没有加载过教师数据，则加载
          if (this.teachers.length === 0 && !this.loading) {
            this.getTeachers();
          }
        }
      },
      deep: true,
      immediate: false
    },
    // 监听父组件的批量导入成功的消息, 导入成功后刷新该子组件
    async updateMsg() {
      this.gradeAndSubject = JSON.parse(JSON.stringify(this.schoolOptions));
      this.getGradeList();
      this.getSubjectList();
      this.buildGradeTree();
      
      // 确保默认选中"全部年级"节点
      if (this.treeData && this.treeData.length > 0) {
        this.currentNode = this.treeData[0];
        this.gradeId = 0; // 默认显示全部年级的教师
      }
      
      this.getTeachers();
    },
    subjectId() {
      this.getTeachers();
    },
    genderId() {
      this.getTeachers();
    },
    teacherName() {
      this._debouncedSearch();
    },
  },
  async created() {
    try {
      const { query } = this.$route;
      if (query.page) {
        this.page = Number(query.page);
        let path = this.$route.path;
        this.$router.replace(path);
      }
      
      // 检查 schoolOptions 是否已加载
      if (this.schoolOptions && this.schoolOptions.F_grades && Object.keys(this.schoolOptions.F_grades).length > 0) {
        this.gradeAndSubject = JSON.parse(JSON.stringify(this.schoolOptions));
        this.getGradeList();
        this.getSubjectList();
        this.buildGradeTree();
        
        // 确保默认选中"全部年级"节点
        if (this.treeData && this.treeData.length > 0) {
          this.currentNode = this.treeData[0];
          this.gradeId = 0; // 默认显示全部年级的教师
        }
        
        await this.getTeachers();
      } else {
        // 如果 schoolOptions 还没有加载，等待 watch 处理
        // watch 中的 schoolOptions 监听器会在数据加载后自动初始化
        console.log('teacherComp: schoolOptions 尚未加载，等待 watch 处理');
      }
      
      // 初始化性别列表
      this.genderList = [
        { id: 0, name: '-' },
        { id: 1, name: '男' },
        { id: 2, name: '女' }
      ];
    } catch (error) {
      console.error('初始化教师数据出错:', error);
      this.$toast('加载教师数据失败，请刷新页面重试');
      this.loading = false;
    }
    
    // 初始化防抖函数（放在try-catch外面，确保总是被创建）
    this._debouncedSearch = debounce(() => {
      this.page = 1;
      this.getTeachers();
    }, 500);
    
    // 添加事件总线监听器
    this.$bus.$on('open-teacher-import-dialog', this.importTeacher);
    this.$bus.$on('open-teacher-export-dialog', this.exportTeacher);
  },
  mounted() {
    this.calculateTableHeight();
    window.addEventListener('resize', this.calculateTableHeight);
  },
  beforeUnmount() {
    // 在组件销毁前移除事件监听，避免内存泄漏
    this.$bus.$off('open-teacher-import-dialog', this.importTeacher);
    this.$bus.$off('open-teacher-export-dialog', this.exportTeacher);
    
    // 清理防抖函数
    if (this._debouncedSearch && this._debouncedSearch.cancel) {
      this._debouncedSearch.cancel();
    }
    
    // 移除窗口大小监听
    window.removeEventListener('resize', this.calculateTableHeight);
  },
  methods: {
    ...mapActions('school', ['GET_SCHOOL_OPTIONS']),
    
    // 处理输入变化时的搜索
    inputChange() {
      this._debouncedSearch();
    },
    
    // 构建年级树形结构
    buildGradeTree() {
      if (!this.gradeList || this.gradeList.length === 0) {
        this.treeData = [];
        return;
      }
      
      const allGrades = {
        id: 'all',
        label: '全部年级',
        count: 0
      };
      
      const gradeNodes = this.gradeList.map(grade => ({
        id: `grade_${grade.id}`,
        label: grade.name,
        count: 0,
        gradeId: grade.id
      }));
      
      this.treeData = [allGrades, ...gradeNodes];
      
      // 如果当前没有选中节点，默认选中全部年级
      if (!this.currentNode) {
        this.currentNode = this.treeData[0];
      }
      
      // 强制树重新渲染以应用当前选中状态
      this.$nextTick(() => {
        if (this.$refs.gradeTree && this.currentNode) {
          this.$refs.gradeTree.setCurrentKey(this.currentNode.id);
        }
      });
    },
    
    // 处理节点点击事件
    handleNodeClick(data) {
      this.currentNode = data;
      this.gradeId = data.id === 'all' ? 0 : data.gradeId;
      this.page = 1;
      this.getTeachers();
    },
    
    batchResetPwd() {
      this.showResetPassword = true;
    },
    async clearAllTeacher() {
      this.$EleMessageBox
        .confirm('是否确认清空老师？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(async () => {
          this.loading = true;
          try {
            const { F_responseNo, F_responseMsg } =
              await this.$api.clearTeachers({
                F_school_id: this.schoolId,
                F_grade: this.gradeId,
                F_subject_id: this.subjectId,
                F_gender: this.genderId,
                F_name: this.teacherName,
              });
            if (F_responseNo === 10000) {
              this.$toast('清空老师成功', 1200);
              // await this.getGradeAndSubject();
              this.getTeachers(true); // 清空后需要更新年级树
            } else {
              this.$toast(`清空老师失败:${F_responseMsg}`, 1500);
            }
            this.loading = false;
          } catch (e) {
            this.loading = false;
            console.error(e);
            this.$toast('清空老师失败', 1200);
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    importTeacher() {
      this.$import(this.schoolId, this.$maps.importType.TEACHER, async () => {
        this.$toast('批量导入老师数据成功');
        await this.GET_SCHOOL_OPTIONS({
          school_id: this.schoolId,
        });
        this.gradeAndSubject = JSON.parse(JSON.stringify(this.schoolOptions));
        this.getGradeList();
        this.getSubjectList();
        this.getTeachers();
      });
    },
    updateTeacher() {
      this.$import(
        this.schoolId,
        this.$maps.importType.UPDATE_TEACHER,
        async () => {
          this.$toast('批量更新老师数据成功');
          await this.GET_SCHOOL_OPTIONS({
            school_id: this.schoolId,
          });
          this.gradeAndSubject = JSON.parse(JSON.stringify(this.schoolOptions));
          this.getGradeList();
          this.getSubjectList();
          this.buildGradeTree();
          this.getTeachers();
        }
      );
    },
    async exportTeacher() {
      this.loading = true;
      try {
        const res = await this.$api.exportSchoolTeacher({
          F_school_id: this.schoolId,
          F_grade: this.gradeId,
          F_subject_id: this.subjectId,
          F_gender: this.genderId,
          F_name: this.teacherName,
        });
        console.log(res);
        downloadExcelBlob(res, `${this.schoolName}老师信息`);
      } catch (e) {
        console.error(e);
        this.$toast('导出老师信息失败,请联系后台管理员');
      }
      this.loading = false;
    },

    getGradeList() {
      this.gradeList = [];
      const { F_grades } = this.gradeAndSubject;
      const processedGradeIds = new Set(); // 用于跟踪已处理的年级ID
      
      for (let gradeId in F_grades) {
        const numGradeId = Number(gradeId);
        
        // 确保不处理重复的年级ID
        if (!processedGradeIds.has(numGradeId)) {
          processedGradeIds.add(numGradeId);
          
          const res = this.$maps.gradeList.find((e) => e.id === numGradeId);
          if (res) this.gradeList.push({...res}); // 使用展开运算符创建新对象
        }
      }
      
      // 不在这里添加"全部年级"，而在buildGradeTree中添加
      // this.gradeList.unshift({ id: 0, name: '全部年级' });
    },
    getSubjectList() {
      this.subjectList = JSON.parse(JSON.stringify(this.schoolSubjectList));
      this.subjectList.unshift({ id: 0, name: '全部科目' });
      this.subjectList.push({ id: -1, name: '未授课' });
    },
    
    async getTeachers(updateTree = true) {
      if (this.schoolId == null) {
        this.loading = false;
        this.$toast('未查询到该账号下的学校列表');
        return;
      }

      
      this.loading = true;
      const res = await this.$api.getTeachers({
        F_grade: this.gradeId,
        F_subject: this.subjectId,
        F_gender: this.genderId,
        F_name: this.teacherName,
        F_page: this.page,
        F_limit: 10,
        F_school_id: this.schoolId,
      });
      this.loading = false;
      this.teacherCount = res.F_total;
      this.teacherAllCount = res.F_all_total;
      this.teachers = res.F_teachers || [];
      this.teachersInfo = [];
      this.teachers.forEach((item) => {
        const { F_teach_list, F_teacher, F_manager_class } = item;
        // 使用本地定义的genderList而不是$maps.genderList
        const genderItem = this.genderList.find(
          (e) => e.id === F_teacher.F_gender
        );
        const F_gender_name = genderItem ? genderItem.name : '-';
        const teach_subject_list = [];
        (F_teach_list || []).forEach((e) => {
          const subject = this.schoolSubjectList.find(
            (u) => u.id === e.F_subject
          );
          if (subject) {
            e.F_subject_name = subject.name;
            if (!teach_subject_list.some((e) => e.id === subject.id)) {
              teach_subject_list.push(subject);
            }
          } else {
            e.F_subject_name = '';
          }
        });
        teach_subject_list.sort((a, b) => a.id - b.id);
        this.teachersInfo.push({
          ...F_teacher,
          F_gender_name,
          F_teach_list,
          F_manager_class,
          teach_subject_list,
        });
      });
      
      // 仅在需要时更新树形结构中的教师数量
      if (updateTree) {
        this.updateGradeTeacherCount();
      }
    },
    
    // 更新年级教师数量
    async updateGradeTeacherCount() {
      if (!this.treeData || this.treeData.length === 0) return;
      
      try {
        // 优化：使用一次API请求获取所有年级的教师数量，而不是为每个年级单独请求
        const res = await this.$api.getTeachers({
          F_grade: 0, // 获取全部年级
          F_subject: this.subjectId,
          F_gender: this.genderId,
          F_name: this.teacherName,
          F_page: 1,
          F_limit: 1000, // 获取足够多的记录以便计算每个年级的数量
          F_school_id: this.schoolId,
        });
        
        const teachers = res.F_teachers || [];
        
        // 计算每个年级的教师数量
        const gradeCounts = {};
        teachers.forEach(teacher => {
          const gradeTeachlists = teacher.F_teach_list || [];
          // 提取教师授课的所有年级
          const teachGrades = new Set();
          gradeTeachlists.forEach(teach => {
            if (teach.F_grade) {
              teachGrades.add(teach.F_grade);
            }
          });
          
          // 更新每个年级的教师计数
          teachGrades.forEach(gradeId => {
            gradeCounts[gradeId] = (gradeCounts[gradeId] || 0) + 1;
          });
        });
        
        // 更新树形数据中的教师数量
        // 创建新数组以触发响应式更新
        this.treeData = this.treeData.map(node => {
          if (!node) return node;
          
          // 创建新对象以确保响应式更新
          const newNode = { ...node };
          
          if (newNode.id === 'all') {
            // 更新"全部"节点的数量
            newNode.count = this.teacherAllCount || 0;
            return newNode;
          }
          
          // 查找对应年级的数量
          const gradeCount = gradeCounts[newNode.gradeId] || 0;
          newNode.count = gradeCount;
          
          return newNode;
        });
        
        // Vue 3 的响应式系统会自动更新视图，不需要手动刷新
      } catch (error) {
        console.error('获取年级教师数量失败:', error);
      }
    },
    
    changePage(val) {
      this.page = val;
      this.getTeachers(false); // 分页不需要更新年级树
    },

    handleCommand(command) {
      switch (command) {
        case 'add-teacher':
          this.addTeacher();
          break;
        case 'import-teacher':
          this.importTeacher();
          break;
        default:
          break;
      }
    },

    addTeacher() {
      this.type = this.$maps.type.ADD;
      this.teacher = {
        F_manage_list: [],
        F_teach_list: [],
        F_teacher: {
          F_name: '',
          F_phone: '',
          F_gender: 1,
        },
      };
      this.isAddTeacher = true;
      this.showEditTeacher = true;
    },
    async editTeacher(item) {
      const { F_responseMsg, F_responseNo, ...teacherInfo } =
        await this.$api.getTeacher({
          F_teacher_id: item.F_id,
        });
      teacherInfo.F_teach_list.forEach((e) => {
        e.F_subject_name =
          this.schoolSubjectList.find((u) => u.id === e.F_subject)?.name ?? '';
      });
      this.type = this.$maps.type.EDIT;
      this.teacher = teacherInfo;
      this.isAddTeacher = false;
      this.showEditTeacher = true;
    },
    deleteTeacher(index, item) {
      const { F_id, F_name } = item;
      this.$delete(F_name, async () => {
        this.loading = true;
        try {
          const { F_responseNo, F_responseMsg } = await this.$api.deleteTeacher(
            {
              F_school_id: this.schoolId,
              F_teacher_id: F_id,
            }
          );
          if (F_responseNo === 10000) {
            this.$toast('删除该老师成功', 1000);
            // 判断当前删除的项是最后一项，且是最后一页的第一个，此时需page-1
            if (
              index === 0 &&
              this.teacherCount % 10 === 1 &&
              this.teacherCount !== 1 &&
              this.page === Math.ceil(this.teacherCount / 10)
            )
              this.page = this.page - 1;
            this.getTeachers(true); // 删除后需要更新年级树，因为可能影响教师数量
          } else this.$toast(`删除该老师失败:${F_responseMsg}`);
        } catch (e) {
          console.error(e);
          this.$toast('删除该老师失败');
        }
        this.loading = false;
      });
    },
    async updateEdit(val) {
      if (!val) {
        this.showEditTeacher = false;
        return;
      }
      const { F_teacher, F_teach_list, F_manage_list } = val;
      // if (F_teach_list.length === 0) {
      //   this.$toast('请选择老师教学班级');
      //   return;
      // }
      const formData = new FormData();
      if (!this.isAddTeacher) F_teacher['F_teacher_id'] = F_teacher.F_id;
      for (let i in F_teacher) {
        formData.append(i, F_teacher[i]);
      }
      const teach_list = [];
      F_teach_list.forEach((e) => {
        const {
          F_id: F_class_id,
          F_grade: F_grade_id,
          F_subject: F_subject_id,
        } = e;
        teach_list.push({
          F_class_id,
          F_grade_id,
          F_subject_id,
        });
      });
      const manage_list = [];
      F_manage_list.forEach((e) => {
        const { F_id: F_class_id } = e;
        manage_list.push({
          F_class_id,
        });
      });
      formData.append('F_school_id', this.schoolId);
      formData.append('F_teach_list', JSON.stringify(teach_list));
      formData.append('F_manage_list', JSON.stringify(manage_list));
      let api = async () => {};
      let text = '';
      if (this.isAddTeacher) {
        api = this.$api.addTeacher;
        text = '添加老师';
      } else {
        api = this.$api.updateTeacher;
        text = '编辑教师信息';
      }
      // this.loading = true;
      try {
        const { F_responseNo, F_responseMsg } = await api(formData);
        if (F_responseNo === 10000) {
          this.$toast(`${text}成功`);
          this.getTeachers(true); // 编辑后需要更新年级树，因为可能改变了教师的所属年级
          this.showEditTeacher = false;
        } else this.$toast(`${text}失败：${F_responseMsg}`);
      } catch (e) {
        console.error(e);
        this.$toast(`${text}失败`);
      }
      // this.isAddTeacher = false;
      // this.loading = false;
    },
    
    // 刷新树节点数据
    refreshTreeData() {
      try {
        // Vue 3 中，由于 treeData 是响应式的，直接更新 this.treeData 即可
        // Element Plus 的 el-tree 会自动响应数据变化
        // 不需要直接操作 $refs.gradeTree.data，因为它是只读的 prop
        if (this.$refs.gradeTree) {
          // 强制触发更新：通过更新 key 来强制重新渲染
          // 或者直接更新 treeData，Vue 的响应式系统会自动更新视图
          this.$forceUpdate();
        }
      } catch (error) {
        console.error('更新树节点数据失败:', error);
      }
    },
    calculateTableHeight() {
      // 获取视窗高度
      const viewportHeight = window.innerHeight;
      
      // 计算表格可用高度
      // 减去页面头部、导航栏、搜索区域、按钮区域、分页区域等的高度
      const headerHeight = 86; // 页面头部高度
      const searchHeight = 60; // 搜索区域高度
      const buttonHeight = 50; // 按钮区域高度
      const paginationHeight = 56; // 分页区域高度
      const padding = 40; // 各种内边距
      
      const availableHeight = viewportHeight - headerHeight - searchHeight - buttonHeight - paginationHeight - padding;
      
      // 设置最小高度为 300px，确保在小屏幕上也有合理的显示效果
      const minHeight = 300;
      const calculatedHeight = Math.max(availableHeight, minHeight);
      
      this.tableMaxHeight = `${calculatedHeight}px`;
    },
  },
};
</script>

<style lang="less" scoped>
.teacher-component {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden; // 防止整体溢出
  
  .teacher-layout {
    flex: 1;
    display: flex;
    min-height: 0; // 重要：允许子元素收缩
    overflow: hidden; // 防止布局溢出
  }

  .grade-tree-container {
    width: 220px;
    background-color: #fff;
    border-right: 1px solid #e6e6e6;
    height: 100%;
    overflow: hidden;
    padding: 0;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;

    .tree-header {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 0;
      padding: 15px;
      border-bottom: 1px solid #e6e6e6;

      flex-shrink: 0;
      z-index: 2;
    }

    .tree-content {
      flex: 1;
      overflow: auto;
      display: flex;
      flex-direction: column;
      padding: 0 10px 10px;
      
      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-thumb {
        background-color: rgba(144, 147, 153, 0.3);
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-track {
        background-color: transparent;
      }
    }

    .el-tree {
      width: 100%;
      font-size: 14px;
      padding: 0;
      margin-top: 5px;

      :deep(.el-tree-node__content) {
        height: 36px;
        
        &:hover {
          background-color: #f5f7fa;
        }
      }
      
      :deep(.is-current > .el-tree-node__content) {
        background-color: #ecf5ff;
      }

      :deep(.custom-tree-node) {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
      }

      :deep(.node-selected) {
        color: #409EFF;
        font-weight: bold;
      }

      :deep(.count-tag) {
        font-size: 12px;
        color: #909399;
        font-weight: normal;
      }
    }

    .empty-tree {
      text-align: center;
      padding: 40px 20px;
      color: #909399;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      flex: 1;

      i {
        font-size: 32px;
        margin-bottom: 10px;
      }

      p {
        margin: 10px 0 0;
      }
    }
  }

  .teacher-list-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    margin-left: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    height: 100%;
    overflow: hidden;
    min-height: 0; // 重要：允许容器收缩

    .grade-info-header {
      padding: 16px 20px;
      border-bottom: 1px solid #e6e6e6;
      background-color: #fff;
      flex-shrink: 0;
      z-index: 2;

      .header-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;

        .grade-title {
          display: flex;
          flex-direction: column;
          gap: 4px;
          
          h2 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
            color: #303133;
            line-height: 1.2;
          }
          
          .subtitle {
            font-size: 14px;
            color: #909399;
            font-weight: normal;
          }
        }

        .search-section {
          display: flex;
          align-items: center;
          gap: 10px;

          .filter-select {
            width: 130px;
          }

          .search-input {
            width: 260px;
          }
        }
      }
    }

    .scrollable-content {
      flex: 1;
      overflow: auto;
      padding: 0 20px;
      display: flex;
      flex-direction: column;
      min-height: 0; // 重要：允许内容区域收缩

      .teacher-section {
        padding: 20px 0;
        display: flex;
        flex-direction: column;
        flex: 1;
        min-height: 0;

        .action-buttons {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          margin-bottom: 16px;
          gap: 8px;
          flex-wrap: wrap;
          
          .el-button {
            margin: 0;
            padding: 8px 16px;
            font-size: 13px;
            
            &.el-button--small {
              padding: 7px 15px;
            }
          }
        }

        .table-wrapper {
          margin-bottom: 15px;
          flex: 1;
          display: flex;
          flex-direction: column;
          min-height: 200px;
          overflow: hidden; // 确保容器不会溢出
          
          :deep(.el-table) {
            flex: 1;
            
            &__body-wrapper {
              overflow-y: auto;
              // 自定义滚动条样式
              &::-webkit-scrollbar {
                width: 8px;
              }
              
              &::-webkit-scrollbar-thumb {
                background-color: rgba(144, 147, 153, 0.3);
                border-radius: 4px;
                
                &:hover {
                  background-color: rgba(144, 147, 153, 0.5);
                }
              }
              
              &::-webkit-scrollbar-track {
                background-color: transparent;
              }
            }
            
            &__row {
              transition: background-color 0.2s;
              
              &:hover {
                background-color: #f5f7fa;
              }
              
              td {
                padding: 12px 0;
                border-bottom: 1px solid #ebeef5;
              }
            }
            
            &__header th {
              padding: 12px 0;
              font-weight: 600;
              background-color: #f5f7fa;
            }
          }
          
          :deep(.table-header) {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: 600;
          }
          
          .cell-content {
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
            justify-content: center;
            align-items: center;
            
            .subject-tag {
              margin: 2px;
            }
            
            .manager-tag {
              margin: 2px;
            }
            
            .teach-class-item {
              font-size: 12px;
              line-height: 1.5;
              padding: 2px 0;
            }
            
            .empty-text {
              color: #c0c4cc;
              font-size: 13px;
            }
          }
          
          .action-buttons-cell {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            
            .edit-btn {
              color: #409EFF;
              
              &:hover {
                color: #66b1ff;
              }
            }
            
            .delete-btn {
              color: #f56c6c;
              
              &:hover {
                color: #f78989;
              }
            }
          }
        }

        .footer {
          text-align: right;
          padding: 10px 0;
          margin-top: auto;
          height: 56px;
          display: flex;
          justify-content: flex-end;
          align-items: center;
          flex-shrink: 0; // 防止分页区域被压缩
        }
      }
    }
  }
}
</style>
